const MD5 = require('../../utils/MD5.js');
// pages/orders/orders.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        totalNum:0,
        total:0,
        params:{},
        address: {
        "userName":'',
        "all":'',
        "telNumber":"",
        },
        order: []
    },
    siteUrl(){
        wx.navigateTo({
          url: '/pages/addsite/addsite',
        })
    },
    //立即付款
    pay: function(_payInfo, success, fail) {
        var payInfo = {
            body: '',
            total_fee: 0,
            order_sn: ''
        }
        Object.assign(payInfo, _payInfo);
        if (payInfo.body.length == 0) {
            wx.showToast({
                title: '支付信息描述错误'
            })
            return false;
        }
        if (payInfo.total_fee == 0) {
            wx.showToast({
                title: '支付金额不能0'
            })
            return false;
        }
        if (payInfo.order_sn.length == 0) {
            wx.showToast({
                title: '订单号不能为空'
            })
            return false;
        }
        var This = this;
        This.getOpenid(function(openid) {
            payInfo.openid = openid;
            This.request({
                url: 'http://api_dev.wanxikeji.cn/api/generateOrder',
                data: payInfo,
                success: function(res) {
                    var data = res.data;
                    console.log(data);
                    if (!data.status) {
                        wx.showToast({
                            title: data['errmsg']
                        })
                        return false;
                    }
                    This.request({
                        url: 'http://api_dev.wanxikeji.cn/api/generateOrder',
                        data: { prepay_id: data.data.data.prepay_id },
                        success: function(_payResult) {
                            var payResult = _payResult.data;
                            // console.log(payResult);
                            wx.requestPayment({
                                'timeStamp': payResult.timeStamp.toString(),
                                'nonceStr': payResult.nonceStr,
                                'package': payResult.package,
                                'signType': payResult.signType,
                                'paySign': payResult.paySign,
                                'success': function(succ) {
                                    success && success(succ);
                                },
                                'fail': function(err) {
                                    fail && fail(err);
                                },
                                'complete': function(comp) {

                                }
                            })
                        }
                    })
                }
            })
        })
    },
    /*统一支付接口*/
    unitedPayRequest(res) {
        //统一支付签名
        var appid = res.data.data.appid;//appid必填
        var body = 'JSAPI支付测试';//商品名必填,没有编码不能用中文
        var mch_id = res.data.data.mch_id;//商户号必填
        var sign = res.data.data.paySign;
        var spbill_create_ip = '192.168.0.178';
        var nonce_str = res.data.data.nonce_str;//随机字符串，不长于32位。  
        var notify_url = 'https://api.mch.weixin.qq.com'; //通知地址必填
        var total_fee = parseInt(0.01 * 100); //价格，这是一分钱
        var trade_type = "JSAPI";
        var out_trade_no = '1212121212';//自定义订单号必填
    
        // var unifiedPayment = 'appid=' + appid + '&body=' + body + '&mch_id=' + mch_id + '&nonce_str=' + nonce_str + '&notify_url=' + notify_url + '&sign' + sign + '&out_trade_no=' + out_trade_no + '&total_fee=' + total_fee + '&trade_type=' + trade_type +'&spbill_create_ip' + spbill_create_ip;
        // // console.log("unifiedPayment", unifiedPayment);
        // var sign = MD5.md5(unifiedPayment).toUpperCase();
        // console.log(res.data.data.sign);
        console.log(sign);
    
        //封装统一支付xml参数
        var formData = "<xml>";
        formData += "<appid>" + appid + "</appid>";
        formData += "<body>" + body + "</body>";
        formData += "<mch_id>" + mch_id + "</mch_id>";
        formData += "<nonce_str>" + nonce_str + "</nonce_str>";
        formData += "<notify_url>" + notify_url + "</notify_url>";
        formData += "<sign>" + sign + "</sign>";
        formData += "<out_trade_no>" + out_trade_no + "</out_trade_no>";
        formData += "<total_fee>" + total_fee + "</total_fee>";
        formData += "<trade_type>" + trade_type + "</trade_type>";
        formData += "<sign>" + sign + "</sign>";
        formData += "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>";
        formData += "</xml>";
        console.log("formData", formData);
        //统一支付
        wx.request({
        url: 'https://api.mch.weixin.qq.com/pay/unifiedorder', //别忘了把api.mch.weixin.qq.com域名加入小程序request白名单，这个目前可以加
        method: 'POST',
        head: 'application/json',
        data: formData, //设置请求的 header
        success: function (res) {
            console.log("返回商户", res.data);
            // var result_code = that.getXMLNodeValue('result_code', res.data.toString("utf-8"));
            // var resultCode = result_code.split('[')[2].split(']')[0];
            // if (resultCode == 'FAIL') {
            // var err_code_des = that.getXMLNodeValue('err_code_des', res.data.toString("utf-8"));
            // var errDes = err_code_des.split('[')[2].split(']')[0];
            // wx.showToast({
            //     title: errDes,
            //     icon: 'none',
            //     duration: 3000
            // })
            // } else {
            // //发起支付
            // var prepay_id = that.getXMLNodeValue('prepay_id', res.data.toString("utf-8"));
            // var tmp = prepay_id.split('[');
            // var tmp1 = tmp[2].split(']');
            // //签名  
            // var key = 'xxx';//商户key必填，在商户后台获得
            // var appId = 'xxx';//appid必填
            // var timeStamp = that.createTimeStamp();
            // var nonceStr = that.randomString();
            // var stringSignTemp = "appId=" + appId + "&nonceStr=" + nonceStr + "&package=prepay_id=" + tmp1[0] + "&signType=MD5&timeStamp=" + timeStamp + "&key=" + key;
            // console.log("签名字符串", stringSignTemp);
            // var sign = md5.md5(stringSignTemp).toUpperCase();
            // console.log("签名", sign);
            // var param = { "timeStamp": timeStamp, "package": 'prepay_id=' + tmp1[0], "paySign": sign, "signType": "MD5", "nonceStr": nonceStr }
            // console.log("param小程序支付接口参数", param);
            // that.processPay(param);
            // }
        },
        })
    },
    handleChooseAddress(){//获取地址
        wx.navigateTo({
          url: '../addsite/addsite',
        })
    },
    pay(res){ //页面跳转
        wx.request({
            url: 'http://api_dev.wanxikeji.cn/api/generateOrder',
            method:'POST',
            data: {
                token:wx.getStorageSync("token"),
                address_id:wx.getStorageSync("bb").address_id,
                money:this.data.total,
                shopping_car_ids:wx.getStorageSync("bb").shopping_car_ids,
            },
            success: (res) => {
                // this.unitedPayRequest(res);
                wx.requestPayment({
                    timeStamp: res.data.data.timeStamp,
                    nonceStr: res.data.data.nonce_str,
                    package: 'prepay_id='+res.data.data.prepay_id,
                    signType: 'MD5',
                    paySign: res.data.data.paySign,
                    success (res) { 
                        console.log(res);
                        let dl = wx.getStorageSync("bb").shopping_car_ids;
                        dl.forEach(v =>{
                            wx.request({//删除购物车列表
                                url: 'http://api_dev.wanxikeji.cn/api/shoppingCarDelete',
                                method:'POST',
                                data: {
                                  token:wx.getStorageSync("token"),
                                  shopping_car_id:v
                                },
                                success: (res) => {
                                //   console.log(res,7777777777);
                                    wx.reLaunch({
                                        url: '../index/index',
                                    })
                                }
                              })
                        })
                    },
                    fail (res) { }
                });
                }
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) { //订单列表
        wx.request({
            url: 'http://api_dev.wanxikeji.cn/api/orderList',
            method:'POST',
            data: {
                token:wx.getStorageSync("token"),
            },
            success: (res) => {
                // console.log(res,22222222);
                let a = [];
                a = res.data.data.data[0].childern;
                a.forEach((i)=>{
                    i.sku = JSON.parse(i.sku);
                    let goods = wx.getStorageSync("goods");
                    for(let j = 0;j<goods.length;j++){
                        if(goods[j].goods_id==i.good_id){
                            i.num = goods[j].goods_number
                        }
                    }
                    this.data.totalNum += i.num;
                    this.data.total += i.price*i.num;
                });
                if(this.data.total>=300){
                    this.data.total = (this.data.total*0.8-20).toFixed(2)
                }else{
                    this.data.total = (this.data.total*0.8+10).toFixed(2)
                }
                this.setData({
                    order:a,
                    total:this.data.total,
                    totalNum:this.data.totalNum,
                });
            }
        });
        wx.request({
            url: 'http://api_dev.wanxikeji.cn/api/userCouponList',
            method:'POST',
            data: {
                token:wx.getStorageSync("token"),
            },
            success: (res) => {
                // console.log(res,22222223333333);
            }
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        wx.request({
            url: 'http://api_dev.wanxikeji.cn/api/userAddressList',
            method:'POST',
            data: {
                token:wx.getStorageSync("token"),
            },
            success: (res) => {
                // console.log(res,3232323232);
                res.data.data.forEach(item =>{
                    if(item.default===1){
                        this.setData({
                            address:{
                                userName:item.name,
                                telNumber:item.phone,
                                all:item.detailed
                            }
                        });
                    }
                })
                
            }
        });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})